package com.seeyon.apps.kkARPEvent.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpClientUtils {
	private static final Log log = LogFactory.getLog(HttpClientUtils.class);

	// post
	public static String postMethod(String url, String query,String token) throws IOException {
		URL restURL = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
		conn.setRequestMethod("POST");
//	     conn.setRequestProperty("Accept-Charset", "UTF-8");
		conn.setRequestProperty("Content-Type", "application/json");
		conn.setRequestProperty("appID", "4916EBDE5F324B1FB05408847F94AF1E");
		conn.setRequestProperty("auth-token", token);


		conn.setDoOutput(true);
		OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
		osw.write(query);
		osw.flush();
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
		String line;
		String result = "";
		while ((line = br.readLine()) != null) {
			result += line;
		}
		br.close();
		log.info(result);
		return result;
	}

	public static String getMethod(String url) throws IOException {
		URL restURL = new URL(url);

		HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();

		conn.setRequestMethod("GET"); // POST GET PUT DELETE
		conn.setRequestProperty("Accept", "application/json");
		conn.setRequestProperty("appID", "4916EBDE5F324B1FB05408847F94AF1E");
		conn.setRequestProperty("keySecret", "797C9A2E449E40EDB57449C7BAA161F8");

		conn.setReadTimeout(5000);
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
		String line;
		StringBuffer sb = new StringBuffer();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		log.info(sb.toString());
		return sb.toString();
	}
	
}
